import {Component, OnInit} from '@angular/core';
import {NzCascaderOption} from 'ng-zorro-antd/cascader';
import {SelectDeviceComponent} from '../../commidity-mamage/select-device/select-device.component';
import {NzModalService} from 'ng-zorro-antd/modal';
import {OutStoreSelectDeviceComponent} from './out-store-select-device/out-store-select-device.component';
import {UsedStorePService} from '../../used-store-p.service';
import {NzMessageService} from 'ng-zorro-antd/message';
import {FinanceOutDetailService} from '../../../finance/finance-out-detail/finance-out-detail.service';
import {ActivatedRoute} from '@angular/router';

interface BaseData {
  id: '';
  title: string; // 出库标题
  type: number; // 出库类型(1、销售出库 2、回收退货 3、不良品返厂 4、物料出库 5、不良品作废)
  remark: string; // 备注
  number: any; // 出库数量
  deliveryMethod: 1 | 2 | 3; // 发货方式(1 顺丰发货 2其他快递 3线下配送)
  expressCode: string;
  expressNo: string;
  isFreight: number;
  freight: any;
  supId: string; // 供应商id
  consignee: string; // 收货人
  tel: string; // 电话
  districtId: []; // 地址库ID
  address: string; // 买家具体地址
}

interface Device {
  number: string; // 出库数量
  price: string; // 出库单价
  libraryId: string; // 库存位置id
  colourId: string; // 成色标识id
  colourName: string; // 成色标识
  modelName: string; // 机型名称
  modelId: string; // 所属机型id
  clinchTime: string; // 成交入库时间
  equipmentCode: string; // 机器编码
  firstTime: string; // 首次入库时间
}

@Component({
  selector: 'app-out-store-add',
  templateUrl: './out-store-add.component.html',
  styleUrls: ['./out-store-add.component.scss']
})
export class OutStoreAddComponent implements OnInit {
  formData: BaseData = {
    id: '',
    title: '',
    number: null,
    type: 0,
    remark: '',
    deliveryMethod: 3,
    expressCode: '',
    expressNo: '',
    isFreight: 1,
    freight: null,
    supId: '',
    consignee: '',
    tel: '',
    districtId: [],
    address: '',
  };
  devices: any[] = [];
  logistics: any[] = [];
  addressArea: any;
  outStoreTypes: any;
  supplierOptions: any;
  /** load data async execute by `nzLoadData` method */
  loadData = (node: NzCascaderOption, index: number) => {
    return new Promise((resolve: any) => {
      // setTimeout(() => {
      if (index < 0) {
        node.children = this.addressArea.province;
      } else if (index === 0) {
        // @ts-ignore
        node.children = this.addressArea.city[node.value];
      } else {
        // @ts-ignore
        node.children = this.addressArea.county[node.value];
        // node.children = scenicspots[node.value];
      }
      resolve();
// }, 1000);
    });
  };

  constructor(
    private nzModalService: NzModalService,
    private usedStorePService: UsedStorePService,
    private nzMessageService: NzMessageService,
    private financeOutDetailService: FinanceOutDetailService,
    private activatedRoute: ActivatedRoute,
  ) {
  }

  async ngOnInit() {
    import('../../../../../assets/city').then(m => {
      const op: any = m.default;
      let list = [];
      list = op.province;
      console.log(list);
      list.forEach((p: any) => {
        p.children = p?.value ? op.city[p.value] : [];
        p.children.forEach((c: any) => {
          c.children = c?.value ? op.county[c.value] : [];
        });
      });
      this.addressArea = list;
    });
    await this.usedStorePService.dictData('machine_inbound_type').then((res: any) => {
      if (res.code === 0) {
        this.outStoreTypes = res.data.list.records.filter((i: any) => i.field2 === 'y');
      }
    });
    await this.usedStorePService.dictData('logistics_company').then((res: any) => {
      if (res.code === 0) {
        this.logistics = res.data.list.records;
      }
    });
    await this.financeOutDetailService.getSupplierData({page: 1, pageSize: 9999}).then((res: any) => {
      if (res.code === 0) {
        this.supplierOptions = res.data.records;
      }
    });
    if (this.activatedRoute.snapshot.queryParams?.id) {
      this.usedStorePService.outStoreDetail(this.activatedRoute.snapshot.queryParams?.id).then(res => {
        if (res.code === 0) {
          const detail = res.data.delivery;
          this.formData = {
            id: detail.id,
            title: detail.title,
            number: detail.number,
            type: detail.type,
            remark: detail.remark,
            deliveryMethod: detail.deliveryMethod,
            expressCode: detail.expressCode,
            expressNo: detail.expressNo,
            isFreight: detail.isFreight,
            freight: detail.freight,
            // @ts-ignore
            supId: detail.supId * 1,
            consignee: detail.consignee,
            tel: detail.tel,
            districtId: [],
            address: detail.address,
          };
          this.setArea(detail.districtId);
          this.devices = res.data.list;
        }
      });
    }
  }

  selectDevice() {
    const modal = this.nzModalService.create({
      nzTitle: '选择设备',
      nzContent: OutStoreSelectDeviceComponent,
      nzFooter: null,
      nzWidth: '1100px',
      nzMaskClosable: false,
      nzComponentParams: {
        equipmentCodes: JSON.stringify(this.devices.map(item => item.equipmentCode))
      },
    });
    modal.afterClose.toPromise().then(res => {
      res?.data.forEach((i: any) => {
        if (this.devices.some((d: any) => d.equipmentCode === i.equipmentCode)) {
          return;
        }
        // @ts-ignore
        this.devices = [...this.devices, i];
      });
    });
  }

  removeDevice(equipmentCode: any) {
    this.devices = this.devices.filter((i: any) => i.equipmentCode !== equipmentCode);
  }

  save() {
    if (!this.formData.title) {
      this.nzMessageService.warning('请输入标题');
      return;
    }
    if (this.formData.number > 0) {
      if (this.formData.number < this.devices.length) {
        this.nzMessageService.warning('出库明细不能大于出库数量，请检查后重试');
        return;
      }
      if (this.formData.number > this.devices.length && !this.formData.remark) {
        this.nzMessageService.warning('出库明细小于出库数量，请在备注中说明相关原因');
        return;
      }
    }
    if (this.formData.deliveryMethod === 2 && !this.formData.expressCode) {
      this.nzMessageService.warning('请选择物流公司');
      return;
    }
    if (this.formData.deliveryMethod === 2 && !this.formData.expressNo) {
      this.nzMessageService.warning('请输入物流单号');
      return;
    }
    if (!this.formData.type) {
      this.nzMessageService.warning('请选择出库类型');
      return;
    }
    if (this.formData.deliveryMethod !== 3) {
      if (!this.formData.consignee) {
        this.nzMessageService.warning('请输入收货人');
        return;
      }
      if (!this.formData.tel) {
        this.nzMessageService.warning('请输入联系方式');
        return;
      }
      if (!this.formData.districtId) {
        this.nzMessageService.warning('请选择地区');
        return;
      }
      if (!this.formData.address) {
        this.nzMessageService.warning('请输入详细地址');
        return;
      }
    }
    if (!this.devices.length) {
      this.nzMessageService.warning('请选择设备');
      return;
    }
    // Reflect.deleteProperty(this.formData, 'remark');
    this.usedStorePService.outStoreSave({
      recycleDelivery: {
        ...this.formData,
        districtId: this.formData.districtId[this.formData.districtId.length - 1]
      },
      list: this.devices.map(d => ({
        number: 1,
        // price: d.realValuation,
        libraryId: d.libraryId,
        colourId: d.colourId,
        colourName: d.colourName,
        modelName: d.modelName,
        modelId: d.modelId,
        clinchTime: d.clinchTime,
        equipmentCode: d.equipmentCode,
        firstTime: d.firstTime,
      }))
    }, !!this.formData.id).then(res => {
      if (res.code === 0) {
        this.nzMessageService.success('操作成功');
        this.back();
      }
    });
  }

  back() {
    window.history.go(-1);
  }

  supplierChange() {
    this.formData.districtId = [];
    if (this.formData.supId) {
      const supplier = this.supplierOptions.filter((s: any) => s.id === this.formData.supId)[0];
      this.formData.consignee = supplier.contacts;
      this.formData.tel = supplier.phoneNumber;
      this.setArea(supplier.districtId);
      this.formData.address = supplier.detailedAddress;
    }
  }

  // 地区 设置默认值
  setArea(districtId: any) {
    districtId = districtId * 1;
    if (!districtId) {
      return;
    }
    this.formData.districtId = [];
    this.addressArea.forEach((p: any) => {
      p.children.forEach((c: any) => {
        c.children.forEach((m: any) => {
          if (districtId === m.value) {
            // @ts-ignore
            this.formData.districtId = [p.value, c.value, m.value];
          }
        });
      });
    });
  }

  // 地区 设置默认值
  // setArea(districtId: any) {
  //   if (!districtId) {
  //     return;
  //   }
  //   this.formData.districtId = [];
  //   // 省
  //   for (const key in this.addressArea.province) {
  //     let province = this.addressArea.province[key];
  //     // 市
  //     for (const k in this.addressArea.city[province.id]) {
  //       let city = this.addressArea.city[province.id][k];
  //       // 区
  //       for (let index = 0; index < this.addressArea.county[city.id].length; index++) {
  //         const county = this.addressArea.county[city.id][index];
  //         if (county.id === districtId) {
  //           // @ts-ignore
  //           this.formData.districtId.push(province.id);
  //           // @ts-ignore
  //           this.formData.districtId.push(city.id);
  //           // @ts-ignore
  //           this.formData.districtId.push(county.id);
  //           break;
  //         }
  //       }
  //     }
  //   }
  // }
}
